package com.haochang.chunkvod.tools.vod.event;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;

/**
 * one k can relationship to many V,<br/>
 * and you can add many K also.
 * @author xingbo.jie
 *
 * @param <K>
 * @param <V>
 */
public class OneToManyHashMap<K, V>
{
	private HashMap<K, ArrayList<V>> mMap;

	public OneToManyHashMap()
	{
		mMap = new HashMap<K, ArrayList<V>>(8);
	}

	public void put(K key, V value)
	{
		ArrayList<V> list = mMap.get(key);

		if (list == null)
		{
			list = new ArrayList<V>();
			mMap.put(key, list);
		}

		if (!list.contains(value))
		{
			list.add(value);
		}
	}

	public boolean containsKey(K key)
	{
		return mMap.containsKey(key);
	}

	public ArrayList<V> get(K key)
	{
		return mMap.get(key);
	}

	public boolean containsValue(V value)
	{
		Iterator<ArrayList<V>> it = mMap.values().iterator();
		while (it.hasNext())
		{
			ArrayList<V> list = it.next();
			if (list.contains(value))
				return true;
		}
		return false;
	}

	public int size()
	{
		return mMap.size();
	}

	public boolean isEmpty()
	{
		return mMap.isEmpty();
	}

	public void clear()
	{
		mMap.clear();
	}

	/**
	 * Removes the mapping with the specified key from this map
	 * @param key
	 */
	public ArrayList<V> remove(K key)
	{
		return mMap.remove(key);
	}

	/**
	 * Removes the mapping with the specified key to the value from this map
	 * @param key
	 * @param value
	 */
	public void remove(K key, V value)
	{
		ArrayList<V> list = mMap.get(key);

		if (list != null)
		{
			list.remove(value);
		}

	}

	/**
	 * Removes the mapping with the specified value from this map
	 * @param value
	 */
	public void removeValue(V value)
	{
		Iterator<ArrayList<V>> it = mMap.values().iterator();
		while (it.hasNext())
		{
			it.next().remove(value);
		}
	}

	public Set<K> keySet()
	{
		return mMap.keySet();
	}

	public Collection<ArrayList<V>> values()
	{
		return mMap.values();
	}

	public Set<Entry<K, ArrayList<V>>> entrySet()
	{
		return mMap.entrySet();
	}
}
